package com.leinao.config;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 
 * Redis连接池配置
 *
 * @author  wangshoufa 
 * @date 2018年11月16日 下午1:50:13
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    private Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
    
    @Autowired
    EnvironmentConfig env;

    private static JedisPool jedisPool;

    /**
     * redis连接工厂
     */
    @Bean
    public JedisPool redisPoolFactory() {
        logger.info("redis url: " + env.getHost() + ":" + env.getPort());
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(env.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(env.getMaxWaitMillis());
        if(StringUtils.isEmpty(env.getPassword())) {
        	 jedisPool = new JedisPool(jedisPoolConfig, env.getHost(), env.getPort(), env.getTimeout());
        } else {
        	 jedisPool = new JedisPool(jedisPoolConfig, env.getHost(), env.getPort(), env.getTimeout(),env.getPassword());
        }
        return jedisPool;
    }

    /**
     * 获取Redis连接池
     */
    public JedisPool getJedisPool(){
    	if(null == jedisPool){
    		redisPoolFactory();
    	}
    	return jedisPool;
    }
}